import { defineStore } from 'pinia';
import { getMenuList } from '@/api/upms/menu';
import { RouteRecordRaw } from 'vue-router';
import { MenuState, Menu } from './types';

const components = import.meta.glob('@/views/**/index.vue');
const modules = Object.fromEntries(
  Object.entries(components).map(([k, v]) => [k.slice(5, -4), v])
);
const useMenuStore = defineStore('menu', {
  state: (): MenuState => ({
    serverMenu: [],
  }),

  getters: {
    asyncMenus(state: MenuState): RouteRecordRaw[] {
      return state.serverMenu as RouteRecordRaw[];
    },
  },

  actions: {
    generatorDynamicRouter(menuList: Menu[], parent: string): RouteRecordRaw[] {
      return menuList?.map((item) => {
        const {
          component,
          name,
          icon,
          path,
          sort,
          title,
          noAffix,
          ignoreCache,
        } = item;
        // ??为NULL判断运算符，运算符左侧的值为null或undefined时，才会返回右侧的值
        const children = item.children ?? [];
        const meta = {
          icon,
          title,
          sort,
          noAffix: noAffix === '1',
          ignoreCache: ignoreCache === '0',
        };
        const isChild = children != null && children.length !== 0;
        const currentRouter: RouteRecordRaw = {
          //  路由地址动态拼接生成如 /dashboard/workplace
          path: parent ? `${parent}/${path}` : `${path || ''}`,
          name,
          meta,
          children: [],
          // 动态导入页面
          component:
            !component || component === 'Layout'
              ? () => import('@/layout/default-layout.vue')
              : modules?.[component],
        };
        // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
        if (!currentRouter.path.startsWith('http')) {
          currentRouter.path = currentRouter.path.replace('//', '/');
        }
        // 是否有子菜单，并递归处理
        if (isChild) {
          currentRouter.children = this.generatorDynamicRouter(
            children,
            currentRouter.path
          );
        }
        return currentRouter;
      });
    },
    async fetchServerMenuConfig() {
      const data = await getMenuList();
      this.serverMenu = this.generatorDynamicRouter(data, '');
    },
    clearServerMenu() {
      this.serverMenu = [];
    },
  },
});

export default useMenuStore;
